/**
 * 
 */

package com.andrew.apolloMod.ui.fragments.grid;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import net.tsz.afinal.http.AjaxCallBack;

import org.gl.android.utils.lg;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Fragment;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.RemoteException;
import android.provider.MediaStore.Audio;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.Spinner;
import android.widget.Toast;

import com.andrew.apolloMod.Constants;
import com.andrew.apolloMod.fm.Channel;
import com.andrew.apolloMod.fm.DouBan;
import com.andrew.apolloMod.helpers.utils.MusicUtils;
import com.andrew.apolloMod.service.ApolloService;
import com.andrew.apolloMod.ui.adapters.DouBanFMAdapter;
import com.andrew.apolloMod.views.PullToRefreshView;
import com.andrew.apolloMod.views.PullToRefreshView.OnFooterRefreshListener;
import com.andrew.apolloMod.views.PullToRefreshView.OnHeaderRefreshListener;
import com.gl.apolloMod.R;

/**
 * fragment for DouBan FM API
 * 
 * @author GeLiang
 * @see {@link http://douban.fm/j/mine/playlist}
 */
public class DouBanFMFragment extends Fragment implements OnItemClickListener,
		OnItemSelectedListener {

	private String key[] = new String[] { "title", "albumtitle", "artist",
			"picture" };
	// Adapter
	private DouBanFMAdapter mAlbumAdapter;

	// GridView
	private GridView mGridView;

	// Options
	private final int PLAY_SELECTION = 3;

	private final int ADD_TO_PLAYLIST = 4;

	private final int SEARCH = 5;
	private final int PLAY_SELECTION_NO = -1;
	private DouBan mDouBan;

	// Bundle
	public DouBanFMFragment() {
	}

	// public DouBanFMFragment(Bundle args) {
	// setArguments(args);
	// }

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		mGridView.setOnCreateContextMenuListener(this);
		mGridView.setOnItemClickListener(this);
		mDouBan = new DouBan();
		getchannels();
		
	}

	Channel mChannels;

	private void getchannels() {
		mDouBan.getChannels(new AjaxCallBack<Channel>() {
			@Override
			public void onSuccess(Channel mChannel) {
				ArrayList<String> list = new ArrayList<String>();
				mChannels = mChannel;
				for (int i = 0; i < mChannel.getChannels().size(); i++) {
					list.add(mChannel.getChannels().get(i).getName());
				}
				ArrayAdapter<String> adapter = new ArrayAdapter<String>(
						getActivity(), android.R.layout.simple_spinner_item,
						list);
				spinner1.setAdapter(adapter);
				spinner1.setOnItemSelectedListener(DouBanFMFragment.this);
				getData(mChannels.getChannels()
						.get(spinner1.getSelectedItemPosition())
						.getChannel_id(), true);
			}
		});

	}

	protected void getData(String channel_id, final boolean isfreash) {
		mDouBan.getPlayList(channel_id, new AjaxCallBack<String>() {
			@Override
			public void onSuccess(String t) {
				super.onSuccess(t);
				try {
					JSONObject result = new JSONObject(t);
					JSONArray ja = result.optJSONArray("song");
					int count = ja.length();
					contents.removeAll(contents);
					if (isfreash) {
						list = ja;
						pullToRefreshView1.onHeaderRefreshComplete();
					} else {
						for (int i = 0; i < count; i++) {
							list.put(ja.optJSONObject(i));
						}
						pullToRefreshView1.onFooterRefreshComplete();
					}
					for (int i = 0; i < list.length(); i++) {
						Map<String, Object> map = new HashMap<String, Object>();
						JSONObject temp = list.getJSONObject(i);
						for (String key1 : key) {
							Object o = temp.opt(key1);
							if (o == null) {
								o = "";
							}
							map.put(key1, o.toString());
						}
						contents.add(map);
					}
					if (isfreash) {
						mAlbumAdapter = new DouBanFMAdapter(getActivity(),
								contents, R.layout.gridview_items, key,
								new int[] { R.id.gridview_line_one,
										R.id.gridview_line_two,
										R.id.gridview_line_three,
										R.id.gridview_image });
						mGridView.setTextFilterEnabled(true);
						mGridView.setAdapter(mAlbumAdapter);
						mGridView.setOnItemClickListener(DouBanFMFragment.this);
						mGridView.setFocusable(true);
						mGridView.requestFocus();
					} else {
						mAlbumAdapter.notifyDataSetChanged();
					}

					Log.i(getTag(), "getData onSuccess :");
				} catch (JSONException e) {
					e.printStackTrace();
				}

			}
		});

	}

	List<Map<String, Object>> contents = new ArrayList<Map<String, Object>>();
	protected JSONArray list;

	PullToRefreshView pullToRefreshView1;
	private Spinner spinner1;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View root = inflater.inflate(R.layout.gridview_pullrefresh, container,
				false);
		pullToRefreshView1 = (PullToRefreshView) root
				.findViewById(R.id.pullToRefreshView1);
		spinner1 = (Spinner) root.findViewById(R.id.spinner1);
		pullToRefreshView1
				.setOnHeaderRefreshListener(new OnHeaderRefreshListener() {
					@Override
					public void onHeaderRefresh(PullToRefreshView view) {
						try {
							MusicUtils.mService.stop();
							getData(mChannels.getChannels()
									.get(spinner1.getSelectedItemPosition()).getChannel_id(),
									true);
						} catch (RemoteException e) {
							e.printStackTrace();
						}

					}
				});
		pullToRefreshView1
				.setOnFooterRefreshListener(new OnFooterRefreshListener() {

					@Override
					public void onFooterRefresh(PullToRefreshView view) {
						getData(mChannels.getChannels()
								.get(spinner1.getSelectedItemPosition()).getChannel_id(),
								false);

					}
				});
		mGridView = (GridView) root.findViewById(R.id.gridview);

		return root;
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View v, final int position,
			long id) {
		Toast.makeText(getActivity(), "loading", Toast.LENGTH_SHORT).show();
		tracksBrowser(position);
	}

	/**
	 * Update the list as needed
	 */
	private final BroadcastReceiver mMediaStatusReceiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			if (mGridView != null && mAlbumAdapter != null
					&& cuttentWebPlayListPostion != PLAY_SELECTION_NO) {
				System.out.println(intent.getAction());
				Bundle buldBundle = intent.getExtras();
				Set<String> buldBundleSet = buldBundle.keySet();
				for (String string : buldBundleSet) {
					System.out.println(string + ":" + buldBundle.get(string));
				}
				if (intent.getAction().equals(ApolloService.META_CHANGED)) {
					// if
					// ((!getString(R.string.unknown).equals(//如果上一次的播放是点击了web音乐列表,那么这里自动读取下个列表
					// buldBundle.getString("track")))
					// &&(! getString(R.string.unknown).equals(
					// buldBundle.getString(Constants.ALBUM_KEY)))
					// && (!getString(R.string.unknown).equals(
					// buldBundle.getString(Constants.ARTIST_KEY)))) {
					// tracksBrowser(cuttentWebPlayListPostion++);
					// }
				} else if (intent.getAction().equals(
						ApolloService.PLAYSTATE_CHANGED)) {
					if ((getString(R.string.unknown).equals(buldBundle
							.getString("track")))
							&& (getString(R.string.unknown).equals(buldBundle
									.getString(Constants.ALBUM_KEY)))
							&& (getString(R.string.unknown).equals(buldBundle
									.getString(Constants.ARTIST_KEY)))) {// 上一次的播放是点击的是web音乐列表,现在完成网络音乐的播放那么这里自动读取下个web歌曲,
																			// FIXME,这种判断不可靠
						// tracksBrowser(cuttentWebPlayListPostion++);
					} else {
						tracksBrowser(PLAY_SELECTION_NO);
					}
				}
				mAlbumAdapter.notifyDataSetChanged();
			}
		}

	};

	@Override
	public void onStart() {
		super.onStart();
		IntentFilter filter = new IntentFilter();
		filter.addAction(ApolloService.META_CHANGED);
		filter.addAction(ApolloService.PLAYSTATE_CHANGED);
		getActivity().registerReceiver(mMediaStatusReceiver, filter);
	}

	@Override
	public void onStop() {
		super.onStop();
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		getActivity().unregisterReceiver(mMediaStatusReceiver);
	}

	int cuttentWebPlayListPostion = PLAY_SELECTION_NO;

	/**
	 * @param index
	 * @param id
	 */
	private void tracksBrowser(int id) {
		if (id < 0 && id > list.length() - 1) {
			return;
		}
		JSONObject song = list.optJSONObject(id);
		Log.i(getTag(), "tracksBrowser" + id);
		if (song != null) {
			try {

				String artistName = song.getString("title");
				String albumName = song.getString("albumtitle");
				String albumId = song.getString("album");
				String url_song = song.getString("url");
				String picture = song.getString("picture");
				Bundle bundle = new Bundle();
				bundle.putString(Constants.MIME_TYPE, Audio.Albums.CONTENT_TYPE);
				bundle.putString(Constants.ARTIST_KEY, artistName);
				bundle.putString(Constants.ALBUM_KEY, albumName);
				bundle.putString(Constants.ALBUM_ID_KEY, albumId);
				bundle.putString(Constants.SONG_URL, url_song);
				bundle.putString(Constants.ALBUM_IMAGE_URL, picture);

				MusicUtils.mService.stop();
				MusicUtils.mService.openFile(url_song);
				// for (int i = id+1; i < list.length(); i++) {//TODO ADD Web
				// Music Stack
				// MusicUtils.mService.enqueueWeb(list.optJSONObject(i).optString("url"));
				// }

				MusicUtils.mService.play();

				// Log.i(getTag(), "tracksBrowser:MusicUtils.mService:" +
				// url_song);
				Intent intent = new Intent(Constants.ACTION_WEB_PLAYER);
				intent.putExtras(bundle);
				getActivity().sendBroadcast(intent);// TODO
				// Log.i(getTag(), "tracksBrowser:sendBroadcast" + url_song);
				cuttentWebPlayListPostion = id;
				mAlbumAdapter.setCurrentSelctPosiont(cuttentWebPlayListPostion);
			} catch (JSONException e) {
				e.printStackTrace();
			} catch (RemoteException e) {
				e.printStackTrace();
			}
		}
	}

	@Override
	public void onItemSelected(AdapterView<?> parent, View view, int position,
			long id) {
		if (parent == spinner1) {
			lg.d(this, mChannels.getChannels()
					.get(spinner1.getSelectedItemPosition()).getChannel_id());
			lg.d(this, mChannels.getChannels()
					.get(spinner1.getSelectedItemPosition()).getName());
			lg.d(this, position);
			getData(mChannels.getChannels()
					.get(spinner1.getSelectedItemPosition()).getChannel_id(),
					true);
		}

	}

	@Override
	public void onNothingSelected(AdapterView<?> parent) {

	}

}
